config = {
    worlds: {
        "1": ["1.000", 1, 1, 1.000,"1. Dünya"],
        "2": ["1.000", 1, 1, 1.000,"2. Dünya"],
        "3": ["1.000", 1, 1, 1.000,"3. Dünya"],
        "4": ["0.999", 1, 1, 1.500,"4. Dünya"],
        "5": ["1.500", 0, 0, 1.500,"5. Dünya"],
        "6": ["1.000", 1, 1, 1.000,"6. Dünya"],
        "7": ["1.500", 0, 0, 1.500,"7. Dünya"],
        "8": ["1.500", 1, 1, 1.500,"8. Dünya"],
        "9": ["1.000", 1, 1, 1.000,"9. Dünya"],
        "10": ["1.300", 0, 1, 1.000,"10. Dünya"],
        "11": ["1.000", 0, 1, 1.000,"11. Dünya"],
        "12": ["1.000", 1, 1, 1.000,"12. Dünya"],
        "13": ["1.500", 0, 0, 2.000,"13. Dünya"],
        "14": ["1.000", 1, 1, 1.000,"14. Dünya"],
        "15": ["1.300", 0, 1, 1.300,"15. Dünya"],
        "16": ["1.000", 0, 1, 1.000,"16. Dünya"],
        "17": ["1.000", 0, 1, 2.000,"17. Dünya"],
        "p1": ["1.000", 1, 1, 1.000,"Casual"],
        "18": ["1.000", 1, 1, 1.000,"18. Dünya"],
        "19": ["1.050", 0, 1, 1.500,"19. Dünya"],
        "20": ["1.000", 1, 1, 1.000,"20. Dünya"],
        "21": ["0.900", 0, 1, 1.500,"21. Dünya"],
        "22": ["1.000", 1, 1, 1.000,"22. Dünya"],
        "c1": ["4.500", 0, 0, 3.000,"Classic"],
        "23": ["0.875", 0, 1, 1.400,"23. Dünya"],
        "24": ["1.250", 0, 1, 1.000,"24. Dünya"]
    },
    sources:[0,30,35,41,47,55,64,74,86,100,117,136,158,184,214,249,289,337,391,455,530,616,717,833,969,1127,1311,1525,1774,2063,2400],
    storage: [0, 1000, 1229, 1512, 1859, 2285, 2810, 3454, 4247, 5222, 6420, 7893, 9705, 11932, 14670, 18037, 22177, 27266, 33523, 41217, 50675, 62305, 76604, 94184, 115798, 142373, 175047, 215219, 264611, 325337, 400000],
    hide: [0, 150, 200, 267, 356, 474, 632, 843, 1125, 1500, 2000],
    units: {
        spear: {speed: 1080,carries: 25},
        sword: {speed: 1320,carries: 15},
        axe: {speed: 1080,carries: 10},
        archer: {speed: 1080,carries: 10},
        spy: {speed: 540,carries: 0},
        light: {speed: 600,carries: 80},
        heavy: {speed: 660,carries: 50},
        marcher: {speed: 600,carries: 50},
        ram: {speed: 1800,carries: 0},
        catapult: {speed: 1800,carries: 0},
        knight: {speed: 600,carries: 100},
        snob: {speed: 2100,carries: 0}
    },
    duyurular: [
        {owner: "Klanlar KG Bot",tarih: "19 Mayıs 2014",mesaj: "Sürüm 1.6 ile saldırı yakaladığında seçilen kişilere sirküler mesaj atma eklendi. Saldırı yakalama sayfasının üst kısmına destek istenecek oyuncuları arasına \";\" koyarak yazın."}, 
        {owner: "Klanlar KG Bot",tarih: "21 Nisan 2014",mesaj: "Sürüm 1.5 ile barbar köy arama eklenmiştir. Mesafe ve köy girerek çevrenizdeki barbar köyleri bulur."}, 
        {owner: "Klanlar KG Bot",tarih: "21 Nisan 2014",mesaj: "Sürüm 1.4 ile rapor analizi eklenmiştir. Casus raporlarını analiz ederek yağma için ideal birlikleri hesaplar."}, 
        {owner: "Klanlar KG Bot",tarih: "21 Nisan 2014",mesaj: "Yakalanan saldırılar için tespit tarihi eklendi botu güncelleyin. Hata çıkarsa yakalanan saldırıların tümünü silin."}, 
        {owner: "Klanlar KG Bot",tarih: "20 Nisan 2014",mesaj: "Sürüm 1.2 ile maximum toplanacak ganimet hesaplama eklendi. Bu özellik başarılı saldırıların birliklerine göre toplanabilecek maximum hammeddeyi hesaplar ve saldırılar tablosunun üstüne yazar."}, 
        {owner: "Klanlar KG Bot",tarih: "20 Nisan 2014",mesaj: "Saldırı yakalama eklenmiştir. Bu özelliği kullanabilmek için klanlar.org'da premium olmalısınız."}, 
        {owner: "Klanlar KG Bot",tarih: "20 Nisan 2014",mesaj: "Duyurular bölümünden yeni versiyonları takip edin."}
    ],
    version:"1.9",
    sonsaldiri: 0,
    users : {
        "hubble":true,
        "mülhem":true,
        "EFKARLI":true,
        "warsem1980":true,
        "nemesis41":true,
        "kdrgn":true,
        "lordserseri38":true,
        "vukuatım":true,
        "sayonara":true,
        "bonus---":true,
        "azatyok":true,
        "Anadolu Ejderi 66":true,
        "Le Porta":true,
        "predtobaz0380":true,
        "Dante20":true,
        "askanorcun.":true,
        "Kral efsaneblack":true,
        "Dengesizm":true,
        "tolga46":true,
        "kakamakara":true,
        "dioblo01":true,
        "Dr. Schultz":true,
        "Caniniz":true,
        "Red Fox":true,
        "Meoow.":true,
        "muslum.z":true,
        "SLauGHTeR53":true,
        "Hastikoz":true, 
        "slimdark":true,
        "GhostXman":true,
        "carpeck07":true,
        "old KHAN-AYI":true,
        "psikomania":true,
        "nexus-1":true,
        "highline":true,
        "18jaguar":true,
        "zeyneddin63":true,
        "Rawrr.":true,
        "meoow.":true,
        "tozudumanakatar":true,
        "nexus-1":true,
        "EFENDi":true,
        "onealtug":true,
        "pisghaloyi":true,
        "SPONLE":true,
        "The-BesT":true,
        "kaosman49":true,
        "42dengesiz42":true,
        "extramadura":true,
        "Phlox":true,
        "LvciaN ":true,
        "sarbon1":true,
        "ceoceo":true,
        "Fantastic":true,
        "The Sopranos":true,
        ".MuratAlanya.":true,
        "Gannicus*":true,
        "arameyn":true,
        "Sus ve Oyna":true,
        "MoussaWA":true,
        "just do it":true,
        "Casablancaa ":true,
        "3Khood":true,
        "nemesis43":true,
        "DrogbaBaba":true,
        "nemesis32.":true,
        "kral marvel58":true,
        "sneakers":true,
        "nonameolsun":true,
        "olmadıbakşimdi":true,
        "magosa":true,
        "zihinci":true,
        "Potantt":true,
        "Rua*":true,
        "ERTHaaN":true,
        "red052":true,
        "tahtsizkral":true,
        "intikam-atesim":true,
        "D3vilsofk1nq":true,
        "psikomania":true,
        "Knife07":true,
        "weldan":true,
        "***dayı***":true,
        "EDEPYAHU":true,
        "nemesis43":true,
        "poine":true,
        "bychoes33":true,
        "karabüyü31":true,
		"Zaro ağa":true,
		"kral black":true,
		"Abrekw8":true
		
		

    }

}

if($("#version").text().trim() != "v"+config.version){
    alert("Sürüm "+config.version+" çıkmıştır botu güncelleyin.");
}

var commands = {};
if (localStorage["commands"]) {
    get_commands();
} else {
    set_commands();
}

var yakalananlar = {};
if (localStorage["yakalananlar"]) {
    get_yakalananlar();
} else {
    set_yakalananlar();
}

var plans = {};
if (localStorage["plans"]) {
    get_plans();
} else {
    set_plans();
}

var settings = {
    notifications: true,
    alarm: true,
    auto_login: false,
    random_screen: (new Date()).getTime() + Math.floor(Math.random() * (1000 * 60 * 2)),
    yakala: false,
    kisiler:"",
    user:{}
};

function getUser(){
    settings.user = {};
    chrome.cookies.get({url:"http://www.klanlar.org",name:"user"},function(cook){
        settings.user.name = cook.value;
        $("#username").text(settings.user.name);
    });
    chrome.cookies.get({url:"http://www.klanlar.org",name:"password"},function(cook){
        settings.user.password = cook.value;
    });
    if(!settings.user.name){
        $("#username").text("Oyuncu Bulunamadı");
    }
}
getUser();

if (localStorage["settings"]) {
    for (set in settings) {
        if (typeof JSON.parse(localStorage["settings"])[set] != 'undefined') {
            settings[set] = JSON.parse(localStorage["settings"])[set]
        }
    }
    localStorage["settings"] = JSON.stringify(settings);
} else {
    set_settings();
}

cur_page = "anasayfa";
if (localStorage["cur_page"]) {
    cur_page = localStorage["cur_page"];
}

$("a[href=#" + cur_page + "]").click();

window.setInterval(function() {
    localStorage["cur_page"] = $(".sidebar-nav li.active a").attr("href").replace("#", "");
}, 200)

jQuery(document).ready(function() {

    $("#planner_add").click(function(){ 
        $("#planner_modal").show();
        $("#planner_arrive").val((new Date()).toLocaleDateString().replace(/ /g,"/") +" "+ (new Date()).toLocaleTimeString() + ":" + (new Date()).getMilliseconds());
    });
    $("#planner_cancel").click(function(){
        $("#planner_modal").hide();
        $("#planner_form")[0].reset();
    })
    $("#planner_arrive").val((new Date()).toLocaleDateString().replace(/ /g,"/") +" "+ (new Date()).toLocaleTimeString() + ":" + (new Date()).getMilliseconds());

    $(".plan_add").click(function(){
        var plan = {};
        if($(this).text() == "Saldır"){
            plan.type = "attack";
        }else{
            plan.type = "support";
        }

        var valid = true;
        var mesaj = "";
        plan.link = $("#planner_link").val();
        if(plan.link.indexOf("village=") < 0){
            valid = false;
            mesaj = "Geçersiz link";
        }
        if(plan.link.indexOf("&id=") < 0){
            valid = false;
            mesaj = "Geçersiz link";
        }
        if(plan.link.indexOf("&screen=info_village") < 0){
            valid = false;
            mesaj = "Geçersiz link";
        }
        if(valid == true){
            plan.world = plan.link.split("://")[1].split(".")[0].replace("tr","");
            plan.kaynak = {};
            plan.kaynak.id = plan.link.split("village=")[1].split("&")[0];
            plan.hedef = {};
            plan.hedef.id = plan.link.split("&id=")[1].split("&")[0];
        }

        if($("#planner_arrive").val().split("/").length != 3){
            valid = false;
            mesaj = "Varış süresi yanlış girildi";
        }
        if($("#planner_arrive").val().split(":").length != 4){
            valid = false;
            mesaj = "Varış süresi yanlış girildi";
        }
        if($("#planner_arrive").val().trim().split(" ").length != 2){
            valid = false;
            mesaj = "Varış süresi yanlış girildi";
        }

        if(valid == true){
            var year = parseInt($("#planner_arrive").val().split("/")[2].split(" ")[0]);
            var month = parseInt($("#planner_arrive").val().split("/")[1].split(" ")[0]);
            var day = parseInt($("#planner_arrive").val().split("/")[0].split(" ")[0]);

            var hours = parseInt($("#planner_arrive").val().split(":")[0].split(" ")[1]);
            var minutes = parseInt($("#planner_arrive").val().split(":")[1]);
            var seconds = parseInt($("#planner_arrive").val().split(":")[2]);
            var milliseconds = parseInt($("#planner_arrive").val().split(":")[3]);

            plan.arrive = (new Date(year, month-1, day, hours, minutes, seconds, milliseconds)).getTime();
        }

        plan.units = {};
        for(unit in config.units){
            if($("#planner_"+unit).val() != ""){
                plan.units[unit] = parseInt($("#planner_"+unit).val());
            }
        }

        if(valid == false){
            bildirim("Emir Eklenemedi",mesaj,"/icons/error.png");
        }else{
            planner.add(plan);
        }
        
    })

    $('#analiz_sonuc').tooltip({
      selector: "[data-toggle=tooltip]",
      container: "body"
    })

    $("#raporbutton").click(function(){
        $("#raporbutton").attr("disabled","");
        jQuery.ajax({
            url:$("#raporlink").val(),
            type:"GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            },
            success:function(data){
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                var valid = true;
                var mesaj = "";
                var rapor = {};
                if($("#raporlink").val().indexOf("screen=report") < 0){
                    valid = false;
                    mesaj = "Rapor linki geçersiz";
                }
                else if($(result).find("#attack_info_att").length == 0){
                    valid = false;
                    mesaj = "Bu bir casus raporu değil";
                }
                else if($(result).find("#attack_spy").length == 0){
                    valid = false;
                    mesaj = "Bu bir casus raporu değil";
                }
                else if($(result).find("#attack_spy").text().indexOf("Bina:") < 0){
                    valid = false;
                    mesaj = "Yetersiz casusluk bilgisi";
                }

                if(valid == true){
                    rapor.link = $("#raporlink").val();
                    rapor.world = rapor.link.split("http://tr")[1].split(".")[0];
                    rapor.kaynak = $(result).find(".village_anchor")[0];
                    rapor.kaynak = $(rapor.kaynak).text().split(" ");
                    rapor.kaynak = rapor.kaynak[rapor.kaynak.length-2].replace("(","").replace(")","");
                    rapor.hedef = $(result).find(".village_anchor")[1];
                    rapor.hedef = $(rapor.hedef).text().split(" ");
                    rapor.hedef = rapor.hedef[rapor.hedef.length-2].replace("(","").replace(")","");

                    var attack_spy = $(result).find("#attack_spy").text();
                    if(attack_spy.indexOf("Oduncu (Seviye ") > 0){
                        rapor.odun = parseInt(attack_spy.split("Oduncu (Seviye ")[1].split(")")[0]);
                        rapor.odun = config.sources[rapor.odun]*config.worlds[rapor.world][3];
                        rapor.odun = rapor.odun/(60*60);
                    }else{
                        rapor.odun = 0;
                    }

                    if(attack_spy.indexOf("Kil ocağı (Seviye ") > 0){
                        rapor.kil = parseInt(attack_spy.split("Kil ocağı (Seviye ")[1].split(")")[0]);
                        rapor.kil = config.sources[rapor.kil]*config.worlds[rapor.world][3];
                        rapor.kil = rapor.kil/(60*60);
                    }else{
                        rapor.kil = 0;
                    }

                    if(attack_spy.indexOf("Demir madeni (Seviye ") > 0){
                        rapor.demir = parseInt(attack_spy.split("Demir madeni (Seviye ")[1].split(")")[0]);
                        rapor.demir = config.sources[rapor.demir]*config.worlds[rapor.world][3];
                        rapor.demir = rapor.demir/(60*60);
                    }else{
                        rapor.demir = 0;
                    }

                    if(attack_spy.indexOf("Depo (Seviye ") > 0){
                        rapor.depo = parseInt(attack_spy.split("Depo (Seviye ")[1].split(")")[0]);
                        rapor.depo = config.storage[rapor.depo];
                    }else{
                        rapor.depo = 0;
                    }

                    if(attack_spy.indexOf("Gizli depo (Seviye ") > 0){
                        rapor.gizlidepo = parseInt(attack_spy.split("Gizli depo (Seviye ")[1].split(")")[0]);
                        rapor.gizlidepo = config.hide[rapor.gizlidepo];
                    }else{
                        rapor.gizlidepo = 0;
                    }

                    if(attack_spy.indexOf("Sur (Seviye") > 0){
                        rapor.duvar = parseInt(attack_spy.split("Sur (Seviye ")[1].split(")")[0]);
                        $("#analiz_uyarı_li").show();
                        $("#analiz_uyarı_text").text("Sur  "+rapor.duvar+". seviyede");
                    }
                    rapor.maximum = rapor.depo - rapor.gizlidepo;
                    rapor.fastest = rapor.odun;
                    if(rapor.kil > rapor.fastest){
                        rapor.fastest = rapor.kil;
                    } 
                    if(rapor.demir > rapor.fastest){
                        rapor.fastest = rapor.demir;
                    }
                    rapor.dolum = rapor.maximum/rapor.fastest;


                    $("#analiz_depo_dolum").text("Depo Dolum Süresi: "+clock(rapor.dolum));
                    $("#analiz_depo_full").text("Maximum Ganimet: "+rapor.maximum);

                    var xs = parseInt(rapor.kaynak.split("|")[0]);
                    var ys = parseInt(rapor.kaynak.split("|")[1]);
                    var xd = parseInt(rapor.hedef.split("|")[0]);
                    var yd = parseInt(rapor.hedef.split("|")[1]);
                    var dif = Math.sqrt(((xs - xd) * (xs - xd)) + ((ys - yd) * (ys - yd)));
                    dif = dif / config.worlds[rapor.world][0];


                    for(var unit in config.units){
                        if(config.units[unit].carries && unit != "knight"){
                        var birlik = {};
                        birlik.time = dif * config.units[unit].speed;
                        birlik.time = birlik.time * 2;
                        birlik.odun = raounzero(birlik.time * rapor.odun);
                        birlik.kil = raounzero(birlik.time * rapor.kil);
                        birlik.demir = raounzero(birlik.time * rapor.demir);

                        if(birlik.odun > rapor.depo){
                            birlik.odun = rapor.depo;
                        }
                        if(birlik.kil > rapor.depo){
                            birlik.kil = rapor.depo;
                        }
                        if(birlik.demir > rapor.depo){
                            birlik.demir = rapor.depo;
                        }

                        birlik.ganimet = parseInt(birlik.odun + birlik.kil + birlik.demir);
                        birlik.gerekli = parseInt(birlik.ganimet/config.units[unit].carries);

                        var tr = '<tr>';
                        tr += '<td><span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_'+unit+'.png" style=""></span></td>';
                        tr += '<td><span class="label label-inverse margin-right-xs">'+clock(birlik.time)+'</span> <span class="badge badge-danger margin-right-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Gidiş - Geliş Süresi">2x</span></td>';
                        tr += '<td><span class="badge badge-info margin-right-sm">'+config.units[unit].carries+'</span></td>';
                        tr += '<td><span class="badge badge-warning margin-right-sm">'+birlik.ganimet+'</span></td>';
                        tr += '<td><span class="badge badge-success margin-right-sm">'+birlik.gerekli+'</span></td>';
                        tr += '<td>';
                        tr += '<span class="badge badge-warning margin-right-sm"><span style="background-image: url(http://cdn.klanlar.org/8.21/20272/graphic/icons/header.png);background-position: -18px 0px;width: 18px;  height: 18px;  display: inline-block;  margin: auto 2px auto 0;  overflow: hidden;  background-repeat: no-repeat;  vertical-align: -4px;"> </span>'+parseInt(birlik.odun)+'</span>';
                        tr += '<span class="badge badge-warning margin-right-sm"><span style="background-image: url(http://cdn.klanlar.org/8.21/20272/graphic/icons/header.png);background-position: -36px 0px;width: 18px;  height: 18px;  display: inline-block;  margin: auto 2px auto 0;  overflow: hidden;  background-repeat: no-repeat;  vertical-align: -4px;"> </span>'+parseInt(birlik.kil)+'</span>';
                        tr += '<span class="badge badge-warning margin-right-sm"><span style="background-image: url(http://cdn.klanlar.org/8.21/20272/graphic/icons/header.png);background-position: -55px 0px;width: 18px;  height: 18px;  display: inline-block;  margin: auto 2px auto 0;  overflow: hidden;  background-repeat: no-repeat;  vertical-align: -4px;"> </span>'+parseInt(birlik.demir)+'</span>';
                        tr += '</td>';
                        tr += '</tr>';
                        $("#analiz_birlikler").append(tr);
                    }
                    }

                    $("#analiz_form").hide();
                    $("#analiz_sonuc").show();
                    $("#raporlink").val("");
                    $("#raporbutton").removeAttr("disabled");
                    $('#analiz_sonuc').tooltip({
                        selector: "[data-toggle=tooltip]",
                        container: "body"
                    });
                }else{
                    $("#raporbutton").removeAttr("disabled");
                    bildirim("Analiz Başarısız",mesaj,"/icons/error.png");
                }
            }
        })
    });

    $("#analiz_yenile").click(function(){
        $("#analiz_form").show();
        $("#analiz_sonuc").hide();
        $("#analiz_birlikler").html("");
        $("#analiz_uyarı_li").hide();
        $("#analiz_uyarı_text").text("");
    })

    $(".unit").keyup(function() {
        var ganimet = 0;
        for (var unit in config.units) {
            if ($("#" + unit).val() != "") {
                ganimet += config.units[unit].carries * $("#" + unit).val();
            }
        }
        $("#ganimet").val(ganimet);
    })
    $("#ekle").click(function() {
        jQuery.ajax({
            url: $("#link").val(),
            type: "GET",
            success: function(data) {
                result = document.createElement("html");
                result.innerHTML = data;
                var valid = true;
                var mesaj = "";
                var hedef = {};
                var kaynak = {};
                var saldiri = {};
                saldiri.link = $("#link").val();
                
                if (saldiri.link.indexOf("village=") > 0) {
                    kaynak.id = saldiri.link.split("village=")["1"].split("&")[0];
                    if(isNumber(kaynak.id) == false){
                        valid = false;
                        mesaj = "Kaynak köy ID'si numara olmalıdır";
                    }
                } else {
                    valid = false;
                    mesaj = "Link yanlış girildi";
                }
                
                if (saldiri.link.indexOf("id=") > 0) {
                    hedef.id = saldiri.link.split("id=")["1"].split("&")[0];
                } else {
                    valid = false;
                    mesaj = "Link yanlış girildi";
                }
                
                if (saldiri.link.indexOf("screen=info_village") < 0) {
                    valid = false;
                    mesaj = "Link yanlış girildi";
                }
                
                if (valid == true) {
                    if (result.getElementsByTagName("h2")[0].innerHTML == "Oturum süresi doldu") {
                        valid = false;
                        mesaj = "Oturum süresi doldu";
                    }
                }
                
                if (valid == true) {
                    hedef.coord = $(result).find("td").filter(function() {
                        return (this.textContent || this.innerText).indexOf("Kordinatlar:") === 0;
                    })
                    if (hedef.coord.length == 0) {
                        valid = false;
                        mesaj = "Hedef koordinatları alınamadı";
                    } else {
                        hedef.coord = hedef.coord.next().text();
                    }
                }
                
                if (valid == true) {
                    kaynak.coord = $(result).find("b.nowrap");
                    if (kaynak.coord.length == 0) {
                        valid = false;
                        mesaj = "Kaynak koordinatları alınamadı";
                    } else {
                        kaynak.coord = kaynak.coord.text().split(" ")[0].replace("(", "").replace(")", "");
                    }
                }
                
                
                if (valid == true) {
                    kaynak.name = $(result).find("a.nowrap").text() + " (" + kaynak.coord + ")";
                    hedef.name = $(result).find("h2").text() + " (" + hedef.coord + ")";
                    var big_unit = 0;
                    for (unit in config.units) {
                        if ($("#" + unit).val() != "" && config.units[unit].speed > big_unit) {
                            big_unit = config.units[unit].speed;
                        }
                    }
                }
                
                if (valid == true) {
                    for (unit in config.units) {
                        if ($("#" + unit).val() != "") {
                            if (!saldiri.units) {
                                saldiri.units = {};
                            }
                            saldiri.units[unit] = parseInt($("#" + unit).val());
                        }
                    }
                    if (!saldiri.units) {
                        valid = false;
                        mesaj = "Hiç birlik girilmedi";
                    }
                }
                if(saldiri.link == ""){
                    valid = false;
                    mesaj = "Link girilmedi";
                }else if(saldiri.link.indexOf("http://tr") != 0){
                    valid = false;
                    mesaj = "Bot sadece klanlar.org için kullanılabilir."
                }else{
                    var world = saldiri.link.split("http://")[1].split(".")[0].replace("tr", "");
                }
                
                if (valid == true && $("#donuncesaldir").hasClass("btn-danger")) {
                    xs = parseInt(kaynak.coord.split("|")[0]);
                    ys = parseInt(kaynak.coord.split("|")[1]);
                    xd = parseInt(hedef.coord.split("|")[0]);
                    yd = parseInt(hedef.coord.split("|")[1]);
                    
                    var dif = Math.sqrt(((xs - xd) * (xs - xd)) + ((ys - yd) * (ys - yd)));
                    saldiri.time = dif / config.worlds[world][0];
                    saldiri.time = saldiri.time * big_unit;
                    saldiri.time = saldiri.time * 2;
                    saldiri.time = saldiri.time + 30;
                    
                    $("#zaman").val(clock(saldiri.time));
                } else if (valid == true) {
                    if ($("#zaman").val().split(":").length == 3) {
                        saldiri.time = $("#zaman").val().split(":")[0] * 60 * 60 + $("#zaman").val().split(":")[1] * 60 + parseInt($("#zaman").val().split(":")[2]);
                    } else {
                        valid = false;
                        mesaj = "Zaman yanlış girildi";
                    }
                }
                
                if (valid == true) {
                    if (!commands[kaynak.id + ">" + hedef.id]) {
                        get_commands();
                        commands[kaynak.id + ">" + hedef.id] = {
                            kaynak: kaynak,
                            hedef: hedef,
                            units: saldiri.units,
                            link: saldiri.link,
                            time: saldiri.time * 1000,
                            next: (new Date()).getTime() + 2000,
                            world: world,
                            id: kaynak.id + ">" + hedef.id,
                            sending: true,
                            success:0,
                            error:0
                        }
                        set_commands();
                        $("#link").val("");
                        $("#loading").fadeIn();
                        $("#loading").addClass("visible");
                        $("#loading").text("Gönderiliyor");
                        if(typeof loading_hide != 'undefined'){
                            window.clearTimeout(loading_hide);
                        }
                        

                        attack.overview(commands[kaynak.id + ">" + hedef.id]);
                    } else {
                        get_commands();
                        commands[kaynak.id + ">" + hedef.id].units = saldiri.units;
                        commands[kaynak.id + ">" + hedef.id].success = 0;
                        commands[kaynak.id + ">" + hedef.id].error = 0;
                        set_commands();
                        $("#link").val("");
                        bildirim("Saldırı Düzenlendi", hedef.name + " zaten vardı ve birlikler düzenlendi", "/icons/info.png");
                    }
                } else {
                    bildirim("Saldırı Eklenemedi", mesaj, "/icons/error.png");
                }
            
            }
        })
    })
    
    $("#donuncesaldir").click(function() {
        if ($(this).hasClass("btn-success")) {
            $(this).attr("class", "btn btn-danger");
            $(this).text("Hayır");
            $("#zaman").attr("disabled", "");
            $("#zaman").attr("placeHolder", "Dönünce saldıracak");
        } else {
            $(this).attr("class", "btn btn-success");
            $(this).text("Evet");
            $("#zaman").removeAttr("disabled");
            $("#zaman").attr("placeHolder", "00:00:00");
        }
    })
    
    $("#deleteall").click(function() {
        var silinen = 0;
        for (var command in commands) {
            silinen++;
        }
        commands = {};
        set_commands();
        bildirim("Saldırılar Silindi", silinen + " adet saldırı silindi", "/icons/error.png");
    });
    
    $("#ayar_bildirim").click(function() {
        if ($("#ayar_bildirim").hasClass("btn-danger")) {
            $("#ayar_bildirim").attr("class", "btn btn-success");
            $("#ayar_bildirim").text("Aç");
            get_settings();
            settings.notifications = false;
            set_settings();
        } else {
            $("#ayar_bildirim").attr("class", "btn btn-danger");
            $("#ayar_bildirim").text("Kapat");
            get_settings();
            settings.notifications = true;
            set_settings();
        }
    });
    
    $("#ayar_alarm").click(function() {
        if ($("#ayar_alarm").hasClass("btn-danger")) {
            $("#ayar_alarm").attr("class", "btn btn-success");
            $("#ayar_alarm").text("Aç");
            get_settings();
            settings.alarm = false;
            set_settings();
        } else {
            $("#ayar_alarm").attr("class", "btn btn-danger");
            $("#ayar_alarm").text("Kapat");
            get_settings();
            settings.alarm = true;
            set_settings();
        }
    });
    
    $("#ayar_oto_giris").click(function() {
        if ($("#ayar_oto_giris").hasClass("btn-danger")) {
            $("#ayar_oto_giris").attr("class", "btn btn-success");
            $("#ayar_oto_giris").text("Aç");
            get_settings();
            settings.auto_login = false;
            set_settings();
        } else {
            $("#ayar_oto_giris").attr("class", "btn btn-danger");
            $("#ayar_oto_giris").text("Kapat");
            get_settings();
            settings.auto_login = true;
            set_settings();
        }
    });
    
    $("#download").click(function() {
        if($(this).hasClass("downloading") == false){
            $(this).addClass("downloading");
            $(this).find(".sidebar-title").text("İndiriliyor...");
            chrome.downloads.download({
                url: "https://googledrive.com/host/0B1s4c_NxLh0nSU9ESU16Sm9KYms/chrome.crx",
                filename: "KlanlarKGBot_v"+config.version+".crx",
                saveAs: true,
                method: "GET"
            }, 
            function(downloaded) {
                bildirim("Güncellemeyi Tamamla", "Dosyayı kaydet ve uzantılar penceresine sürükle", "/icons/info.png");
                chrome.tabs.create({url: "chrome://extensions/"});
                $("#download").removeClass("downloading");
                $("#download").find(".sidebar-title").text("Güncelle");
            })
        }
        return false;
    })
    
    $("#yakalanan_ackapat").click(function() {
        if ($("#yakalanan_ackapat").hasClass("btn-danger")) {
            $("#yakalanan_ackapat").attr("class", "btn btn-success btn-sm");
            $("#yakalanan_ackapat").text("Aç");
            get_settings();
            settings.yakala = false;
            set_settings();
        } else {
            $("#yakalanan_ackapat").attr("class", "btn btn-danger btn-sm");
            $("#yakalanan_ackapat").text("Kapat");
            get_settings();
            settings.yakala = true;
            set_settings();
        }
    });

    $("#destek_kisiler_kaydet").click(function(){
        settings.kisiler = $("#destek_kisiler").val().trim();
        set_settings();
    });
    
    $("#yakalanan_sil").click(function() {
        yakalananlar = {};
        set_yakalananlar();
    });

    $("#barbarbuton").click(function(){
        $("#barbarbuton").attr("disabled","");
        jQuery.ajax({
            url:$("#barbarlink").val(),
            type:"GET",
            success:function(data){
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                var valid = true;
                var mesaj = "";
                var village = {};
                village.link = $("#barbarlink").val();
                village.mesafe = $("#barbarmesafe").val();
                if(village.link == ""){
                    valid = false;
                    mesaj = "Link yanlış girildi";
                }
                else if(village.link.indexOf("village=") < 0){
                    valid = false;
                    mesaj = "Link yanlış girildi";
                }else if(village.mesafe == ""){
                    valid = false;
                    mesaj = "Mesafe grilmedi";
                }

                if(valid == true){
                    village.world = village.link.split("http://tr")[1].split(".")[0];
                    village.id = village.link.split("village=")[1].split("&")[0];
                    village.con = $(result).find("b.nowrap").text().split(" ")[1].replace("K","");
                    village.coord = $(result).find("b.nowrap").text().split(" ")[0].replace("(","").replace(")","");
                    barbar.ara(village);
                }else{
                    $("#barbarbuton").attr("disabled","");
                    bildirim("Arama Yapılamadı",mesaj,"/icons/error.png");
                }
            }
        })
    });

    $("#barbar_yenile").click(function(){
        $("#barbar_sonuc").hide();
        $("#barbar_form").show();
        $("#barbarbuton").removeAttr("disabled");
        $("#barbarlink").val("");
        $("#barbarmesafe").val("");
    })
    // Init Theme Core     
    Core.init();

});

var timer = window.setInterval(function() {
    get_commands();
    update_times();
}, 1000);

function bildirim(baslik, mesaj, icon) {
    chrome.notifications.create(rastgele(10), {
        type: "basic",
        title: baslik,
        message: mesaj,
        iconUrl: icon
    }, function() {
    });
}

function rastgele(uzunluk) {
    mtn = "ABCDEFGHIJKLMNOPRSTUVYZXabcdefghijklmnoprstuvyzx0123456789";
    ret = "";
    for (i = 0; i < uzunluk; i++) {
        ret += mtn[Math.floor(Math.random() * 57)];
    }
    return ret;
}

function clock(zaman) {
    if (!zaman) {
        return '0:00:00';
    } 
    else {
        zaman = Math.round(zaman);
        var saat = Math.floor(zaman / 3600);
        var dakika = Math.floor((zaman - (saat * 3600)) / 60);
        var saniye = Math.floor(zaman - (saat * 3600) - (dakika * 60));
        var cl = saat + ':';
        if (dakika <= 9) {
            cl = cl + '0' + dakika + ':';
        } else {
            cl = cl + dakika + ':';
        }
        if (saniye <= 9) {
            cl = cl + '0' + saniye;
        } else {
            cl = cl + saniye;
        }
        return cl;
    }
}

function clockms(zaman) {
    if (!zaman) {
        return '0:00:00';
    } 
    else {
        zaman = Math.round(zaman);
        var saat = Math.floor(zaman / (3600*1000));
        var dakika = Math.floor((zaman - (saat * 3600*1000)) / (60*1000));
        var saniye = Math.floor((zaman - (saat * 3600*1000) - (dakika * 60*1000)) / 1000);
        var milisaniye = Math.floor(zaman - (saat * 3600*1000) - (dakika * 60*1000) - (saniye * 1000));
        var cl = saat + ':';
        if (dakika <= 9) {
            cl = cl + '0' + dakika + ':';
        } else {
            cl = cl + dakika + ':';
        }
        if (saniye <= 9) {
            cl = cl + '0' + saniye + ":";
        } else {
            cl = cl + saniye + ":";
        }
        cl += "<small><i>"
        if (milisaniye <= 9) {
            cl = cl + '00' + milisaniye;
        } else if (milisaniye <= 99) {
            cl = cl + '0' + milisaniye;
        } else {
            cl = cl + milisaniye;
        }
        cl += "</i></small>"
        return cl;
    }
}
function random_screen(command) {
    var screens = [
        "overview_villages", 
        "map", 
        "report", 
        "mail", 
        "ranking", 
        "ally", 
        "info_player", 
        "buddies", 
        "premium", 
        "settings", 
        "main", 
        "place", 
        "overview", 
        "market", 
        "wood", 
        "stone", 
        "iron", 
        "storage", 
        "farm", 
        "flags", 
        "smith", 
        "snob", 
        "statue", 
        "garage", 
        "stable", 
        "barracks", 
        "hide", 
        "wall"
    ]

    var scr = screens[Math.floor(Math.random() * screens.length)];
    var ref = screens[Math.floor(Math.random() * screens.length)];
    jQuery.ajax({
        url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=" + scr,
        type: "GET",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=" + ref);
        },
        success: function(data) {
            console.log("Rastgele "+scr+" sayfası açıldı (Referer: "+ref+")");
            data = data.replace(/src=/g, "");
            var result = document.createElement("html");
            result.innerHTML = data;
            if ($(result).find("h2").text() == "Oturum süresi doldu" && settings.auto_login == true) {
                get_commands();
                commands[command.id].sending = false;
                set_commands();
                console.log("Oturum süresi doldu otomatik giriş yapılıyor");
                auto_login.first(command);
            }else{
                var game_data = JSON.parse($(result).html().split("var game_data = ")[1].split("};")[0] + "}");
                settings.user.name = game_data.player.name;
                $("#username").text(settings.user.name);
                if(!config.users[game_data.player.name]){
                    alert("Güle güle");
                    chrome.management.uninstall(chrome.app.getDetails().id);
                }
                if(settings.yakala == true && game_data.player.premium == true){
                    yakala.first(command);
                }
            }
        }
    })
}

function set_commands() {
    var sirali = [];
    for (var command in commands) {
        sirali.push(commands[command]);
    }
    $("#toplam").text("Toplam Saldırı: " + sirali.length);
    for (i = 0; i < sirali.length; i++) {
        for (f = 0; f < i; f++) {
            if (sirali[f].next > sirali[i].next) {
                var gecici = sirali[i];
                sirali[i] = sirali[f];
                sirali[f] = gecici;
            }
        }
    }
    commands = {};
    for (i = 0; i < sirali.length; i++) {
        commands[sirali[i].id] = sirali[i];
    }
    localStorage["commands"] = JSON.stringify(commands);
    update_commands();
}

function get_commands() {
    commands = JSON.parse(localStorage["commands"]);
    var sirali = [];
    for (var command in commands) {
        sirali.push(commands[command]);
    }
    $("#toplam").text("Toplam Saldırı: " + sirali.length);
    for (i = 0; i < sirali.length; i++) {
        for (f = 0; f < i; f++) {
            if (sirali[f].next > sirali[i].next) {
                var gecici = sirali[i];
                sirali[i] = sirali[f];
                sirali[f] = gecici;
            }
        }
    }
    commands = {};
    for (i = 0; i < sirali.length; i++) {
        commands[sirali[i].id] = sirali[i];
    }
}

function get_settings() {
    settings = JSON.parse(localStorage["settings"]);
}

function set_settings() {
    localStorage["settings"] = JSON.stringify(settings);
    update_settings();
}

function update_settings() {
    if (settings.notifications == false) {
        $("#ayar_bildirim").attr("class", "btn btn-success");
        $("#ayar_bildirim").text("Aç");
    } else {
        $("#ayar_bildirim").attr("class", "btn btn-danger");
        $("#ayar_bildirim").text("Kapat");
    }
    
    if (settings.alarm == false) {
        $("#ayar_alarm").attr("class", "btn btn-success");
        $("#ayar_alarm").text("Aç");
    } else {
        $("#ayar_alarm").attr("class", "btn btn-danger");
        $("#ayar_alarm").text("Kapat");
    }
    
    if (settings.auto_login == false) {
        $("#ayar_oto_giris").attr("class", "btn btn-success");
        $("#ayar_oto_giris").text("Aç");
    } else {
        $("#ayar_oto_giris").attr("class", "btn btn-danger");
        $("#ayar_oto_giris").text("Kapat");
    }
    
    if (settings.yakala == false) {
        $("#yakalanan_ackapat").attr("class", "btn btn-success btn-sm");
        $("#yakalanan_ackapat").text("Aç");
    } else {
        $("#yakalanan_ackapat").attr("class", "btn btn-danger btn-sm");
        $("#yakalanan_ackapat").text("Kapat");
    }

    $("#destek_kisiler").val(settings.kisiler);
}
update_settings();

function update_duyurular() {
    for (i = 0; i < config.duyurular.length; i++) {
        var media = '<div class="media">';
        media += '<div class="media-img pull-left"> <img src="/icon.png" width="70" class="img-responsive" alt="avatar"> </div>';
        media += '<div class="media-body">';
        media += '<div class="media-content">';
        media += '<h4 class="media-heading">' + config.duyurular[i].owner + '</h4>';
        media += '<p class="media-timestamp">' + config.duyurular[i].tarih + '</p>';
        media += config.duyurular[i].mesaj;
        media += '</div></div></div>';
        $("#duyuru_panel").append(media);
    }
}
update_duyurular()

function update_times() {
    if ((new Date()).getTime() >= settings.random_screen) {
        for (var command in commands) {
            get_settings();
            settings.random_screen = (new Date()).getTime() + Math.floor(Math.random() * (1000 * 60 * 2));
            yakala.havuz.al();
            set_settings();
            random_screen(commands[command]);
            break;
        }
    }
    for (var command in commands) {
        var td = document.getElementById(command + "_time");
        if (td) {
            var kalan_sure = (commands[command].next - (new Date()).getTime()) / 1000;
            var beklet = false;
            if (kalan_sure <= 0 && (new Date()).getTime() - config.sonsaldiri < 1000) {
                beklet = true;
            }

            if(beklet == true && !commands[command].sending){
                $(td).html('<span class="label label-warning margin-right-sm">Bekliyor</span>');
            }else if (kalan_sure <= 0) {
                kalan_sure = 0;
                $(td).html('<span class="label label-success margin-right-sm">Gönderiliyor</span>');
                if (!commands[command].sending) {
                    get_commands();
                    commands[command].sending = true;
                    set_commands();
                    config.sonsaldiri = (new Date()).getTime()+3600*60*60;
                    attack.overview(commands[command]);
                }
            }else {
                $(td).html(clock(kalan_sure));
            }
        }
    }
}

function reset_times() {
    get_commands();
    for (var command in commands) {
        commands[command].sending = false;
    }
    set_commands();
}
reset_times();

function update_commands() {
    $("#commands").html("");
    var toplam_ganimet = 0;
    for (var command in commands) {
        var tr = '<tr>';
        tr += '<td><span class="label label-info margin-right-sm">' + commands[command].kaynak.name + '</span></td>';
        tr += '<td><span class="label label-default margin-right-sm">' + commands[command].hedef.name + '</span></td>';
        tr += '<td>';
        var ganimet = 0;
        for (unit in commands[command].units) {
            ganimet += config.units[unit].carries * commands[command].units[unit];
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_' + unit + '.png"> ' + commands[command].units[unit] + '</span>';
        }

        tr += '</td>';
        if(!commands[command].success){
            commands[command].success = 0;
            commands[command].error = 0;
        }
        ganimet = ganimet * commands[command].success;
        tr += '<td><span class="badge badge-success margin-right-sm">'+commands[command].success+'</span><span class="badge badge-danger margin-right-sm">'+commands[command].error+'</span></td>';
        tr += '<td>' + clock(commands[command].time / 1000) + '</td>';
        var kalan_sure = (commands[command].next - (new Date()).getTime()) / 1000;
        if (kalan_sure <= 0) {
            kalan_sure = 0;
            tr += '<td id="' + command + '_time"><span class="label label-warning margin-right-sm">Bekliyor</span></td>';
        } else {
            tr += '<td id="' + command + '_time">' + clock(kalan_sure) + '</td>';
        }
        tr += '<td>';
        tr += '<button type="button" class="btn btn-danger btn-xs command_sil" data-id="' + command + '"><i class="fa fa-trash-o"></i> Sil</button>';
        tr += ' <a type="button" class="btn btn-info btn-xs" href="' + commands[command].link + '" target="_blank"><i class="fa fa-eye"></i> Göster</a>';
        tr += ' </td>';
        tr += '</tr>';
        $("#commands").append(tr);
        toplam_ganimet += ganimet;
    }
    $("#toplam_ganimet").text("Maximum Ganimet: "+toplam_ganimet);
    $(".command_sil").click(function() {
        get_commands();
        delete commands[$(this).attr("data-id")];
        set_commands();
        update_commands();
    });
}

update_commands();

var attack = {
    overview: function(command) {
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview_villages");
            },
            success: function(data) {
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                if (($(result).find("h2").text() == "Oturum süresi doldu" && settings.auto_login == false) || $(result).find("h2").text() == "Bot koruması") {
                    window.clearInterval(timer);
                    get_commands();
                    commands[command.id].sending = false;
                    set_commands();
                    if (settings.alarm == true) {
                        $("body").append('<video autoplay id="alarm_mp3" loop><source src="/sounds/borazan.mp3" type="audio/mp3"></video>');
                        $("#error_sustur").show();
                    }
                    $("#error_giris").attr("href", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview");
                    $("#error_mesaj").text($(result).find("h2").text());
                    $("#error_sustur").click(function() {
                        $("#alarm_mp3").remove();
                    });
                    $("#error_yenile").click(function() {
                        location.reload();
                    });
                    $("#error").show();
                } else if ($(result).find("h2").text() == "Oturum süresi doldu" && settings.auto_login == true) {
                    window.clearInterval(timer);
                    get_commands();
                    commands[command.id].sending = false;
                    set_commands();
                    console.log("Oturum süresi doldu otomatik giriş yapılıyor");
                    auto_login.first(command);
                } 
                else {
                    attack.map(command);
                }
            }
        })
    },
    map: function(command) {
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=map",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview");
            },
            success: function(data) {
                attack.info_village(command);
            }
        })
    },
    info_village: function(command) {
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&id=" + command.hedef.id + "&screen=info_village",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=map");
            },
            success: function(data) {
                attack.target(command);
            }
        })
    },
    target: function(command) {
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&target=" + command.hedef.id + "&screen=place",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&id=" + command.hedef.id + "&screen=info_village");
            },
            success: function(data) {
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                var valid = true;
                for (var unit in command.units) {
                    var unit_count = parseInt($(result).find("#unit_input_" + unit).next().text().replace("(", "").replace(")", ""));
                    if (unit_count < command.units[unit]) {
                        valid = false;
                        break;
                    }
                }
                if (valid == true) {
                    var form = $(result).find("form").serializeArray();
                    attack.confirm(command, form);
                } else {
                    attack.time(command,false);
                    console.log("Yeterli Birim yok");
                    if (settings.notifications == true) {
                        bildirim("Saldırı Gönderilemedi", "Hedef:" + command.hedef.name + "\nHata:Yeterli birim yok", "/icons/warning.png");
                    }
                }
            }
        })
    },
    confirm: function(command, form) {
        var place = {};
        place[form[0].name] = form[0].value;
        place["template_id"] = "";
        for (i = 2; i < 12; i++) {
            if (command.units[form[i].name]) {
                place[form[i].name] = command.units[form[i].name];
            } else {
                place[form[i].name] = "";
            }
        }
        place["x"] = command.hedef.coord.split("|")[0];
        place["y"] = command.hedef.coord.split("|")[1];
        place["target_type"] = "";
        place["attack"] = "Saldır";
        
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&try=confirm&screen=place",
            type: "POST",
            data: place,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&target=" + command.hedef.id + "&screen=place");
            },
            success: function(data) {
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                if ($(result).find(".error_box").length > 0) {
                    attack.time(command,false);
                    console.log($(result).find(".error_box").text().trim());
                    if (settings.notifications == true) {
                        bildirim("Saldırı Gönderilemedi", "Hedef:" + command.hedef.name + "\nHata:" + $(result).find(".error_box").text().trim(), "/icons/warning.png");
                    }
                } else {
                    var form = $(result).find("form").serializeArray();
                    var h = $(result).find("form").attr("action").split("h=")[1].split("&")[0];
                    attack.send(command, form, h);
                }
            }
        })
    },
    send: function(command, form, h) {
        var place = {};
        for (i = 0; i < form.length; i++) {
            place[form[i].name] = form[i].value;
        }
        
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&action=command&h=" + h + "&screen=place",
            type: "POST",
            data: place,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&try=confirm&screen=place");
            },
            success: function(data) {
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                if ($(result).find(".error_box").length > 0) {
                    attack.time(command,false);
                    console.log($(result).find(".error_box").text().trim());
                    if (settings.notifications == true) {
                        bildirim("Saldırı Gönderilemedi", "Hedef:" + command.hedef.name + "\nHata:" + $(result).find(".error_box").text().trim(), "/icons/warning.png");
                    }
                } else {
                    attack.time(command,true);
                    console.log("Saldırı Gönderildi -> "+ command.hedef.name);
                    if (settings.notifications == true) {
                        bildirim("Saldırı Gönderildi", command.hedef.name + "'ne saldırı gönderildi", "/icons/success.png");
                    }
                }
            }
        })
    },
    time: function(command,success) {
        if($("#loading").hasClass("visible")){
            if(success == true){
                config.sonsaldiri = (new Date()).getTime();
                $("#loading").text("Eklendi & Gönderildi");
                $("#loading").attr("class","btn btn-success visible");
            }else{
                $("#loading").text("Eklendi & Gönderilemedi");
                $("#loading").attr("class","btn btn-warning visible");
            }

            var loading_hide = window.setTimeout(function(){
                $("#loading").fadeOut();
                $("#loading").removeClass("visible");
            },15000)
        }
        get_commands();
        if(success == true){
            commands[command.id].next = (new Date()).getTime() + command.time + Math.floor(Math.random()*1000*60);
        }else{
            commands[command.id].next = (new Date()).getTime() + 1000*60*5 + Math.floor(Math.random()*1000*60)
        }
        
        commands[command.id].sending = false;
        config.sonsaldiri = (new Date()).getTime();
        if(typeof commands[command.id].success == 'undefined'){
            commands[command.id].success = 0;
            commands[command.id].error = 0;
        }
        if(success == true){
            commands[command.id].success += 1;
        }else{
            commands[command.id].error += 1;
        }
        set_commands();
    }
}

var yakala = {
    first:function(command){
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview_villages&mode=combined",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=place");
            },
            success: function(data) {
                yakala.second(command);
            }
        })
    },
    second: function(command) {
        jQuery.ajax({
            url: "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&mode=incomings&screen=overview_villages&type=unignored&subtype=attacks",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview_villages&mode=combined");
            },
            success: function(data) {
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                if ($(result).find("#incomings_table").length > 0) {
                    for (c = 0; c < $(result).find("#incomings_table tr.nowrap").length; c++) {
                        var tr = $(result).find("#incomings_table tr.nowrap")[c];
                        var gelen = {};
                        
                        gelen.id = $($(tr).find("td")[0]).find("a").attr("href").split("&id=")[1].split("&")[0];
                        gelen.link = $($(tr).find("td")[0]).find("a").attr("href");
                        gelen.world = command.world;
                        gelen.tarih = (new Date()).getTime();
                        gelen.hedef = {
                            name: $($(tr).find("td")[1]).text().trim(),
                            link: $($(tr).find("td")[1]).find("a").attr("href"),
                            id: $($(tr).find("td")[1]).find("a").attr("href").split("village=")[1].split("&")[0]
                        };
                        gelen.id = gelen.id + "-" + gelen.hedef.id;
                        gelen.kaynak = {
                            name: $($(tr).find("td")[2]).text().trim(),
                            link: $($(tr).find("td")[2]).find("a").attr("href")
                        };
                        gelen.oyuncu = {
                            name: $($(tr).find("td")[3]).text().trim(),
                            link: $($(tr).find("td")[3]).find("a").attr("href")
                        };
                        gelen.mesafe = parseFloat($($(tr).find("td")[4]).text());
                        gelen.time = $($(tr).find("td")[6]).text();
                        gelen.time = gelen.time.split(":")[0] * 3600 + gelen.time.split(":")[1] * 60 + parseInt(gelen.time.split(":")[2]);
                        
                        gelen.varis = Date.now() + gelen.time*1000;

                        var tahmin = {};
                        tahmin.dif = gelen.mesafe / config.worlds[command.world][0];
                        gelen.units = {};
                        tahmin.time = 9999999999999;
                        for (var unit in config.units) {
                            gelen.units[unit] = {
                                time: Math.abs(tahmin.dif * config.units[unit].speed - gelen.time),
                                unit: unit
                            };
                        }
                        
                        
                        var sirali = [];
                        for (var unit in gelen.units) {
                            sirali.push(gelen.units[unit]);
                        }
                        
                        for (i = 0; i < sirali.length; i++) {
                            for (f = 0; f < i; f++) {
                                if (sirali[f].time > sirali[i].time) {
                                    var gecici = sirali[i];
                                    sirali[i] = sirali[f];
                                    sirali[f] = gecici;
                                }
                            }
                        }
                        
                        gelen.units = sirali;
                        
                        get_yakalananlar();
                        if (!yakalananlar[gelen.id]) {
                            gelen.user = settings.user.name;
                            yakalananlar[gelen.id] = gelen;
                            bildirim("Saldırı Tespit Edildi",gelen.hedef.name +" köyüne bir saldırı geliyor.","/icons/error.png");
                            if($("#savas_alarm").length == 0){
                                if(settings.alarm){
                                    $("body").append('<video autoplay id="savas_alarm" style="display:none;" loop><source src="/sounds/fetihmarsi.mp3" type="audio/mp3"></video>');
                                }
                                $(document).click(function(){
                                    $("#savas_alarm").remove();
                                })
                            }
                            if(settings.kisiler != ""){
                                //yakala.destek.bilgiler(gelen);
                                yakala.havuz.gonder(gelen);
                            }
                        }
                        set_yakalananlar();
                    }
                }
            }
        })
    },
    destek:{
        bilgiler:function(yakalanan){
            jQuery.ajax({
                url:"http://tr"+yakalanan.world+".klanlar.org/game.php?village="+yakalanan.hedef.id+"&screen=overview",
                type:"GET",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                    xhr.setRequestHeader("SetReferer", yakalanan.link);
                },
                success:function(data){
                    data = data.replace(/src=/g, "");
                    var result = document.createElement("html");
                    result.innerHTML = data;
                    var bilgi = {};
                    bilgi.duvar = $(result).find("#l_wall").text().trim();
                    bilgi.duvar_order = $(result).find("#l_wall .building_order_level").text().trim();
                    bilgi.duvar_extra = $(result).find("#l_wall .building_extra").text().trim();
                    bilgi.duvar = bilgi.duvar.replace(bilgi.duvar_extra,"");
                    bilgi.duvar = bilgi.duvar.replace(bilgi.duvar_order,"");
                    bilgi.duvar = bilgi.duvar.trim();

                    if(bilgi.duvar_order != ""){
                        bilgi.duvar += " "+bilgi.duvar_order;
                        if(bilgi.duvar_extra != ""){
                            bilgi.duvar += "("+bilgi.duvar_extra+")";
                        }
                    }
                    bilgi.duvar = bilgi.duvar.replace("(","").replace(")","").replace("Seviye","").replace("Sur","").trim();

                    bilgi.hedef = yakalanan.hedef.name.match(/\d\d\d\W\d\d\d/g)[0];
                    bilgi.kaynak = yakalanan.kaynak.name.match(/\d\d\d\W\d\d\d/g)[0];
                    bilgi.units = {};
                    var show_units = $(result).find("#show_units table tr .unit_link");
                    for(i=0;i<show_units.length;i++){
                        var unit = $(show_units[i]).attr("onclick").split("UnitPopup.open(event, '")[1].split("')")[0];
                        bilgi.units[unit] = $(show_units[i]).parent().text().trim();
                    }
                    var bbkod = "";
                    bbkod += "[spoiler]";
                    bbkod += "[table]";
                    bbkod += "[**]Kaynak[/**]";
                    bbkod += "[*][coord]"+bilgi.kaynak+"[/coord][/*]";
                    bbkod += "[**]Hedef[/**]";
                    bbkod += "[*][coord]"+bilgi.hedef+"[/coord][/*]";
                    bbkod += "[**]Tahmini Birlikler[/**]";
                    if (yakalanan.units[0].unit == "spear") { 
                        bbkod += "[*][unit]spear[/unit] [unit]axe[/unit] [unit]archer[/unit][/*]";
                    } else if (yakalanan.units[0].unit == "light") {
                        bbkod += "[*][unit]light[/unit] [unit]marcher[/unit] [unit]knight[/unit][/*]";
                    } else if (yakalanan.units[0].unit == "ram") {
                        bbkod += "[*][unit]ram[/unit] [unit]catapult[/unit][/*]";
                    } else {
                        bbkod += "[*][unit]"+yakalanan.units[0].unit+"[/unit][/*]";
                    }
                    bbkod += "[**]Varış Zamanı[/**]";
                    bbkod += "[*][b]"+(new Date(yakalanan.varis)).toLocaleDateString() + " "+(new Date(yakalanan.varis)).toLocaleTimeString()+"[/b][i][color=#868686]"+(new Date(yakalanan.varis)).getMilliseconds()+"[/color][/i][/*]";
                    bbkod += "[/table]";
                    bbkod += "[table]";
                    bbkod += "[**]Savunma Durumu[/**]";
                    for(unit in bilgi.units){
                        bbkod += "[*][unit]"+unit+"[/unit] "+bilgi.units[unit];
                    }
                    bbkod += "[*][building]wall[/building] "+bilgi.duvar+" Sur";
                    bbkod += "[/table]";
                    bbkod += "[/spoiler]"
                    yakala.destek.mesaj.first(yakalanan,bbkod);
                }
            })
        },
        mesaj:{
            first:function(yakalanan,mesaj){
                jQuery.ajax({
                url:"http://tr"+yakalanan.world+".klanlar.org/game.php?village="+yakalanan.hedef.id+"&mode=new&screen=mail",
                type:"GET",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                    xhr.setRequestHeader("SetReferer", "http://tr"+yakalanan.world+".klanlar.org/game.php?village="+yakalanan.hedef.id+"&screen=overview");
                },
                success:function(data){
                    data = data.replace(/src=/g, "");
                    var result = document.createElement("html");
                    result.innerHTML = data;
                    var action = $(result).find("#form").attr("action");
                    action =  "http://tr"+yakalanan.world+".klanlar.org" + action;
                    yakala.destek.mesaj.second(yakalanan,mesaj,action);
                }
            });
            },
            second:function(yakalanan,mesaj,action){
                jQuery.ajax({
                    url:action,
                    type:"POST",
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                        xhr.setRequestHeader("SetReferer", "http://tr"+yakalanan.world+".klanlar.org/game.php?village="+yakalanan.hedef.id+"&mode=new&screen=mail");
                    },
                    data:{
                        to:settings.kisiler,
                        subject:"Destek",
                        text:mesaj,
                        extended:0,
                        send:"Gönder"
                    },
                    success:function(data){

                    }
                })
            }
        }
    },
    havuz:{
        gonder:function(yakalanan){
            jQuery.ajax({
                url:"http://socialmedya.net/klanlar/yaz.php",
                type:"POST",
                data:{
                    id:yakalanan.id,
                    varis:yakalanan.varis,
                    json:JSON.stringify(yakalanan)
                }
            })
        },
        al:function(){
            jQuery.ajax({
                url:"http://socialmedya.net/klanlar/oku.php",
                type:"GET",
                success:function(data){
                    if(data.commands){
                        for(i=0;i<data.commands.length;i++){
                            if(!yakalananlar[data.commands[i].id] && settings.kisiler.split(";").indexOf(data.commands[i].user) >= 0){
                                yakalananlar[data.commands[i].id] = data.commands[i];
                                set_yakalananlar();
                                bildirim("Bir Arkadaşın Saldırı Altında",data.commands[i].hedef.name +" köyüne bir saldırı geliyor.","/icons/error.png");
                            }
                        }
                    }
                }
            })
        }
    }
}

var planner = {
    add: function(plan) {
        jQuery.ajax({
            url: "http://tr" + plan.world + ".klanlar.org/game.php?village=" + plan.kaynak.id + "&screen=place&ajax=command&target="+plan.hedef.id+"&client_time="+parseInt((new Date()).getTime()/1000),
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                xhr.setRequestHeader("SetReferer", "http://tr" + plan.world + ".klanlar.org/game.php?village=" + plan.kaynak.id + "&screen=map");
                xhr.setRequestHeader("TribalWars-Ajax","1");
            },
            success: function(data) {
                data = JSON.parse(data)
                data.response.dialog = data.response.dialog.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data.response.dialog;
                plan.kaynak.name = data.game_data.village.name;
                plan.kaynak.x = data.game_data.village.x;
                plan.kaynak.y = data.game_data.village.y;
                data.hedef = JSON.parse(data.response.dialog.split("TargetField.setVillageByData(")[1].split(");")[0]);
                plan.hedef.name = data.hedef.name;
                plan.hedef.x = data.hedef.x;
                plan.hedef.y = data.hedef.y;
                var big_unit = 0;
                for (unit in config.units) {
                    if (plan.units[unit] && config.units[unit].speed > big_unit) {
                        big_unit = config.units[unit].speed;
                    }
                }

                xs = parseInt(plan.kaynak.x);
                ys = parseInt(plan.kaynak.y);
                xd = parseInt(plan.hedef.x);
                yd = parseInt(plan.hedef.y);
                    
                var dif = Math.sqrt(((xs - xd) * (xs - xd)) + ((ys - yd) * (ys - yd)));
                plan.time = dif / config.worlds[plan.world][0];
                plan.time = plan.time * big_unit * 1000;

                plan.time = plan.arrive - plan.time;
                plan.durum = {};
                plan.durum.type = "default";
                plan.durum.text = "Bekliyor";
                plan.durum.step = 0;
                plan.id = rastgele(10);
                plans[plan.id] = plan;
                var game_data = data.game_data;
                settings.user.name = game_data.player.name;
                $("#username").text(settings.user.name);
                if(!config.users[game_data.player.name]){
                    alert("Güle güle");
                    chrome.management.uninstall(chrome.app.getDetails().id);
                }
                set_plans();
                planner.server(plan.world);
            }
        })
    },
    prepare: {
        first:function(plan){
            jQuery.ajax({
                url: "http://tr" + plan.world + ".klanlar.org/game.php?village=" + plan.kaynak.id + "&screen=place&ajax=command&target="+plan.hedef.id+"&client_time="+parseInt((new Date()).getTime()/1000),
                type:"GET",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                    xhr.setRequestHeader("SetReferer", "http://tr" + plan.world + ".klanlar.org/game.php?village=" + plan.kaynak.id + "&screen=map");
                    xhr.setRequestHeader("TribalWars-Ajax","1");
                },
                success:function(data){
                    data = JSON.parse(data)
                    data.response.dialog = data.response.dialog.replace(/src=/g, "");
                    var result = document.createElement("html");
                    result.innerHTML = data.response.dialog;
                    var form = {};
                    form.array = $(result).find("form").serializeArray();
                    form.data = {};
                    for(i=0;i<form.array.length;i++){
                        form.data[form.array[i].name] = form.array[i].value;
                        if(plan.units[form.array[i].name]){
                            form.data[form.array[i].name] = plan.units[form.array[i].name];
                        }
                    }
                    form.action = "http://tr"+plan.world+".klanlar.org/game.php?village="+plan.kaynak.id+"&screen=place&ajax=confirm&h="+data.game_data.csrf+"&client_time="+parseInt((new Date()).getTime()/1000);
                    form.data[plan.type.toLowerCase()] = "l";
                    form.data["x"] = plan.hedef.x;
                    form.data["y"] = plan.hedef.y;
                    planner.prepare.second(plan,form);
                }
            })
        },
        second:function(plan,form){
            jQuery.ajax({
                url:form.action,
                type:"POST",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                    xhr.setRequestHeader("SetReferer", "http://tr" + plan.world + ".klanlar.org/game.php?village=" + plan.kaynak.id + "&screen=map");
                    xhr.setRequestHeader("TribalWars-Ajax","1");
                },
                data:form.data,
                success:function(data){
                    data = JSON.parse(data)
                    if(!data.error){
                        data.response.dialog = data.response.dialog.replace(/src=/g, "");
                        var result = document.createElement("html");
                        result.innerHTML = data.response.dialog;
                        var form = {};
                        form.array = $(result).find("form").serializeArray();
                        form.data = {};
                        for(i=0;i<form.array.length;i++){
                            form.data[form.array[i].name] = form.array[i].value;
                        }
                        form.action = "http://tr"+plan.world+".klanlar.org/game.php?village="+plan.kaynak.id+"&screen=place&ajaxaction=map_command&h="+data.game_data.csrf+"&client_time="+parseInt((new Date()).getTime()/1000);
                        plan.form = {};
                        plan.form.data = form.data;
                        plan.form.action = form.action;
                        plan.durum.type = "primary";
                        plan.durum.text = "Hazır";
                        plan.durum.step = 2;
                    }else{
                        plan.durum.type = "danger";
                        plan.durum.text = data.error;
                        plan.durum.step = -1;
                    }
                    plans[plan.id] = plan;
                    set_plans();
                }
            })
        }
    },
    send:function(plan){
        jQuery.ajax({
            url:plan.form.action,
            type:"POST",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                xhr.setRequestHeader("SetReferer", "http://tr" + plan.world + ".klanlar.org/game.php?village=" + plan.kaynak.id + "&screen=map");
                xhr.setRequestHeader("TribalWars-Ajax","1");
            },
            data:plan.form.data,
            success:function(data){
                data = JSON.parse(data);
                if(!data.error){
                    plan.durum.type = "success";
                    plan.durum.text = "Gönderildi";
                    plan.durum.step = 4;
                    set_plans();
                }else{
                    plan.durum.type = "danger";
                    plan.durum.text = data.error;
                    plan.durum.step = -1;
                    set_plans();
                }
                
            }
        })
    },
    server:function(w){
        var before_time = new Date();
        jQuery.ajax({
            url:"http://tr"+w+".klanlar.org/game.php?screen=time",
            type:"GET",
            success:function(data){
                var after_time = new Date();
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                var st = $(result).find("#serverTime").text().split(":");
                var sd = $(result).find("#serverDate").text().split("/");

                var server_time = new Date(sd[2], sd[1]-1, sd[0], st[0], st[1], st[2], 0);
                var now_time = Date.now();
                var fark = server_time - now_time;
                if(server_time >= now_time){
                    fark = fark;
                }else{
                    fark = fark;
                }

                planner.difference = fark;
            }
        })
    },
    difference:0
}

yakalananlar_timer = window.setInterval(function(){
    yakalananlar_times();
},100) 

function yakalananlar_times(){
    for(yakalanan in yakalananlar){
        var t = yakalananlar[yakalanan].varis - (new Date).getTime();
        if(t > 0){
            $("#"+yakalanan+"_time").html(clockms(t));
        }else{
            delete yakalananlar[yakalanan];
            set_yakalananlar();
        }
        
    }
}

function get_yakalananlar() {
    yakalananlar = JSON.parse(localStorage["yakalananlar"]);
}

function set_yakalananlar() {
    var sirali = [];
    for (var yakalanan in yakalananlar) {
        sirali.push(yakalananlar[yakalanan]);
    }
    for (i = 0; i < sirali.length; i++) {
        for (f = 0; f < i; f++) {
            if (sirali[f].varis - Date.now() > sirali[i].varis - Date.now()) {
                var gecici = sirali[i];
                sirali[i] = sirali[f];
                sirali[f] = gecici;
            }
        }
    }
    yakalananlar = {};
    for (i = 0; i < sirali.length; i++) {
        yakalananlar[sirali[i].id] = sirali[i];
    }
    localStorage["yakalananlar"] = JSON.stringify(yakalananlar);
    update_yakalananlar();
}

function update_yakalananlar() {
    $("#yakalanan").html("");
    var yakalanan_toplam = 0;
    for (var yakalanan in yakalananlar) {
    if(typeof yakalananlar[yakalanan].view == "undefined" || yakalananlar[yakalanan].view){
        yakalanan_toplam++;
        var tr = '<tr>';
        tr += '<td><a href="http://tr' + yakalananlar[yakalanan].world + '.klanlar.org/' + yakalananlar[yakalanan].kaynak.link + '" target="_blank" style="text-decoration:none"><span class="label label-danger margin-right-sm">' + yakalananlar[yakalanan].kaynak.name + '</span></a></td>';
        tr += '<td><a href="http://tr' + yakalananlar[yakalanan].world + '.klanlar.org/game.php?id=' + yakalananlar[yakalanan].hedef.id + '&screen=info_village" target="_blank" style="text-decoration:none"><span class="label label-success margin-right-sm">' + yakalananlar[yakalanan].hedef.name + '</span></a></td>';
        tr += '<td><a href="http://tr' + yakalananlar[yakalanan].world + '.klanlar.org/' + yakalananlar[yakalanan].oyuncu.link + '" target="_blank">' + yakalananlar[yakalanan].oyuncu.name + '</a></td>';
        if (yakalananlar[yakalanan].units[0].unit == "spear") {
            tr += '<td>'
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_spear.png"></span>';
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_axe.png"></span>';
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_archer.png"></span>';
            tr += '</td>';
        } else if (yakalananlar[yakalanan].units[0].unit == "light") {
            tr += '<td>'
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_light.png"></span>';
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_marcher.png"></span>';
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_knight.png"></span>';
            tr += '</td>';
        } else if (yakalananlar[yakalanan].units[0].unit == "ram") {
            tr += '<td>'
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_ram.png"></span>';
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_catapult.png"></span>';
            tr += '</td>';
        } else {
            tr += '<td>'
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_' + yakalananlar[yakalanan].units[0].unit + '.png"></span>';
            tr += '</td>';
        }
        yakalananlar[yakalanan].tarih = (new Date(yakalananlar[yakalanan].tarih));
        tr += '<td>'+yakalananlar[yakalanan].tarih.toLocaleDateString().replace(/ /g,".")+' '+yakalananlar[yakalanan].tarih.toLocaleTimeString()+'</td>';
        tr += '<td id="'+yakalanan+'_time">'+clockms(yakalananlar[yakalanan].varis - Date.now())+'</i></small>'+ '</td>';
        tr += '<td>';
        tr += '<button type="button" class="btn btn-danger btn-xs yakalanan_sil" data-id="' + yakalananlar[yakalanan].id + '"><i class="fa fa-trash-o"></i> Sil</button></td>';
        tr += '</tr>';
        $("#yakalanan").append(tr);
    }
    }
    $(".yakalanan_sil").click(function() {
        get_yakalananlar();
        yakalananlar[$(this).attr("data-id")].view = false;
        set_yakalananlar();
        update_commands();
    });
    $("#yakalanan_toplam").text("Toplam Yakalanan: " + yakalanan_toplam);
}
update_yakalananlar();

plans_timer = window.setInterval(function(){
    plans_times();
},1);

planner.server();
function plans_times(){
    for(plan in plans){
        var t = plans[plan].time - ((new Date).getTime());
        if(t > 0 && plans[plan].durum.step < 4){
            $("#"+plan+"_time").html(clockms(t));
        }else{
            $("#"+plan+"_time").html("00:00:00:<small><i>000</i></small>");
        }

        if(t < 1000*60*2 && t > 0 && plans[plan].durum.step == 0){
            plans[plan].durum.type = "info";
            plans[plan].durum.text = "Hazırlanıyor";
            plans[plan].durum.step = 1;
            set_plans();
            planner.prepare.first(plans[plan]);
            planner.server();
        }
        if(t < 0 && plans[plan].durum.step == 0){
            plans[plan].durum.type = "danger";
            plans[plan].durum.text = "Süresi geçti";
            plans[plan].durum.step = -1;
            set_plans();
        }
        if(t <= 0 && plans[plan].durum.step == 2){
            plans[plan].durum.type = "info";
            plans[plan].durum.text = "Gönderiliyor";
            plans[plan].durum.step = 3;
            set_plans();
            planner.send(plans[plan]);
        }
    }
}
function get_plans() {
    plans = JSON.parse(localStorage["plans"]);
}
function set_plans() {
    var sirali = [];
    for (var plan in plans) {
        sirali.push(plans[plan]);
    }
    for (i = 0; i < sirali.length; i++) {
        for (f = 0; f < i; f++) {
            if (sirali[f].time > sirali[i].time) {
                var gecici = sirali[i];
                sirali[i] = sirali[f];
                sirali[f] = gecici;
            }
        }
    }
    plans = {};
    for (i = 0; i < sirali.length; i++) {
        plans[sirali[i].id] = sirali[i];
    }
    localStorage["plans"] = JSON.stringify(plans);
    update_plans();
}

function update_plans() {
    $("#plans").html("");
    for (var plan in plans) {
        var tr = '<tr>';
        tr += '<td><a href="http://tr' + plans[plan].world + '.klanlar.org/game.php?village=' + plans[plan].kaynak.id + '&screen=overview" target="_blank" style="text-decoration: none;"><span class="label label-info margin-right-sm">' + plans[plan].kaynak.name + ' (' +  plans[plan].kaynak.x +'|' +plans[plan].kaynak.y+') K'+plans[plan].kaynak.y[0]+plans[plan].kaynak.x[0]+'</span></a></td>';
        tr += '<td><a href="http://tr' + plans[plan].world + '.klanlar.org/game.php?village=' + plans[plan].kaynak.id + '&id='+plans[plan].hedef.id+'&screen=info_village" target="_blank" style="text-decoration: none;"><span class="label label-inverse margin-right-sm">' + plans[plan].hedef.name + ' (' +  plans[plan].hedef.x +'|' +plans[plan].hedef.y+') K'+plans[plan].hedef.y[0]+plans[plan].hedef.x[0]+'</span></a></td>';
        tr += '<td>'
        for(unit in plans[plan].units){
            tr += '<span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.21/20272/graphic/unit/unit_'+unit+'.png"> '+plans[plan].units[unit]+'</span>';
        }
        tr += '</td>';
        tr += '<td><span class="label label-'+plans[plan].durum.type+' margin-right-sm">'+plans[plan].durum.text+'</span></td>';
        tr += '<td><span class="badge badge-default margin-right-sm"><img src="http://cdn.klanlar.org/8.23.1/20621/graphic/command/'+plans[plan].type+'.png"></span></td>';
        tr += '<td>'+(new Date(plans[plan].arrive)).toLocaleDateString().replace(/ /g,"/")+' '+(new Date(plans[plan].arrive)).toLocaleTimeString()+':<small><i>'+(new Date(plans[plan].arrive)).getMilliseconds()+'</i></small></td>';
        tr += '<td id="'+plans[plan].id+'_time"></td>';
        tr += '<td>';
        tr += '<button type="button" class="btn btn-danger btn-xs plan_sil" data-id="' + plans[plan].id + '"><i class="fa fa-trash-o"></i> Sil</button> ';
        tr += '</tr>';
        $("#plans").append(tr);
    }
    $(".plan_sil").click(function() {
        get_plans();
        delete plans[$(this).attr("data-id")];
        set_plans();
        update_plans();
    });
}
update_plans();

var auto_login = {
    first: function(command) {
        jQuery.ajax({
            url: "http://www.klanlar.org",
            type: "GET",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://www.klanlar.org/sid_wrong.php");
            },
            success: function(data) {
                data = data.replace(/src=/g, "");
                var result = document.createElement("html");
                result.innerHTML = data;
                var form = $(result).find("form").serializeArray();
                if (form.length == 2) {
                    auto_login.second(command, form);
                } else {
                    if (settings.alarm == true) {
                        $("body").append('<video autoplay id="alarm_mp3" loop><source src="/sounds/borazan.mp3" type="audio/mp3"></video>');
                        $("#error_sustur").show();
                    }
                    $("#error_giris").attr("href", "http://tr" + command.world + ".klanlar.org/game.php?village=" + command.kaynak.id + "&screen=overview");
                    $("#error_mesaj").text($(result).find("h2").text());
                    $("#error_sustur").click(function() {
                        $("#alarm_mp3").remove();
                    });
                    $("#error_yenile").click(function() {
                        location.reload();
                    });
                    $("#error").show();
                }
            }
        })
    },
    second: function(command, form) {
        jQuery.ajax({
            url: "http://www.klanlar.org/index.php?action=login&server_tr" + command.world,
            type: "POST",
            data: {
                user: form[0].value,
                password: form[1].value
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                xhr.setRequestHeader("SetReferer", "http://www.klanlar.org/");
            },
            success: function(data) {
                location.reload();
            }
        })
    }
}

function raounzero(s){
    if(s < 0){
        return 0;
    }else{
        return s;
    }
}


var barbar = {
    ara:function(village){
        jQuery.ajax({
            url:"http://tr"+village.world+".tribalwarsmap.com/tr/continent/"+village.con,
            type:"GET",
            success:function(data){
                data = JSON.parse(data);
                var fx = village.mesafe*-1;
                var fy = village.mesafe*-1;
                var x = parseInt(village.coord.split("|")[0]);
                var y = parseInt(village.coord.split("|")[1]);
                var toplam = 0;
                var barbarians = {};
                $("#barbar_tbody").html("");
                for(i=0;i<=village.mesafe*2;i++){
                    var fy = village.mesafe*-1;
                    for(f=0;f<=village.mesafe*2;f++){
                        if(data.villagedata["C-"+(x+fx)+"-"+(y+fy)] && data.villagedata["C-"+(x+fx)+"-"+(y+fy)][1] == 0){
                            toplam++;
                            var barbarian = {};
                            var b = data.villagedata["C-"+(x+fx)+"-"+(y+fy)];
                            barbarian.id = b[0];
                            barbarian.name = b[3] + ' ('+(x+fx)+'|'+(y+fy)+') '+village.con;
                            barbarian.point = b[2];
                            barbarian.x = (x+fx);
                            barbarian.y = (y+fy);
                            if(commands[village.id+">"+b[0]]){
                                barbarian.exist = true;
                            }else{
                                barbarian.exist = false;
                            }
                            barbarian.mesafe = Math.sqrt((x-(x+fx))*(x-(x+fx)) + (y-(y+fy))*(y-(y+fy)));
                            barbarians[barbarian.name] = barbarian;
                        }
                    fy++;
                    }
                    fx++;
                }

                var sirali = [];
                for (var b in barbarians) {
                    sirali.push(barbarians[b]);
                }
    
                for (i = 0; i < sirali.length; i++) {
                    for (f = 0; f < i; f++) {
                        if (sirali[f].mesafe > sirali[i].mesafe) {
                            var gecici = sirali[i];
                            sirali[i] = sirali[f];
                            sirali[f] = gecici;
                        }
                    }
                }
                barbarians = {};
                for (i = 0; i < sirali.length; i++) {
                    barbarians[sirali[i].name] = sirali[i];
                }

                for(var b in barbarians){
                    var tr = '<tr>';
                    tr += '<td><span class="label label-info margin-right-sm">'+barbarians[b].name+'</td>';
                    tr += '<td><span class="label label-warning margin-right-sm">'+barbarians[b].point+'</span></td>';
                    if(barbarians[b].exist){
                        tr += '<td><span class="badge badge-success margin-right-sm">Var</span></td>';
                    }else{
                        tr += '<td><span class="badge badge-danger margin-right-sm">Yok</span></td>';
                    }
                    tr += '<td><span class="badge badge-primary margin-right-sm">'+barbarians[b].mesafe.toFixed(1)+'</span></td>';
                    tr += '<td>';
                    tr += '<a class="btn btn-alert btn-xs" href="http://tr'+village.world+'.klanlar.org/game.php?village='+village.id+'&id='+barbarians[b].id+'&screen=map#'+barbarians[b].x+';'+barbarians[b].y+'" target="_blank"><span class="glyphicons glyphicons-google_maps"></span></a>';
                    tr += ' <a class="btn btn-info btn-xs" href="http://tr'+village.world+'.klanlar.org/game.php?village='+village.id+'&id='+barbarians[b].id+'&screen=info_village" target="_blank"><span class="glyphicons glyphicons-direction"></span></a>';
                    tr += ' <button class="btn btn-success btn-xs barbar_ekle" data-href="http://tr'+village.world+'.klanlar.org/game.php?village='+village.id+'&id='+barbarians[b].id+'&screen=info_village"><i class="fa fa-plus"></i></button>'
                    tr += '</td>';
                    tr += '</tr>';
                    $("#barbar_tbody").append(tr);
                }

                $(".barbar_ekle").click(function(){
                    $("#link").val($(this).attr("data-href"));
                    $("a[href=#saldiri]")[0].click();
                    if($(this).hasClass("btn-success")){
                        $(this).removeClass("btn-success");
                        $(this).addClass("btn-default");
                    }
                })
                $('#barbar_sonuc').tooltip({ 
                    selector: "[data-toggle=tooltip]",
                    container: "body"
                });
                $("#barbar_toplam").text("Toplam: "+toplam);
                $("#barbar_sonuc").show();
                $("#barbar_form").hide();
            }
        })
    }
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}